import React from 'react';
import { connect } from 'umi';
import { Table, Input, Form, Modal } from 'antd';
import { SelectComDepTree, SelectEmployee } from '@/pages/Flow/components';

// import Position from './Position';
// import styles from './index.less';

let rowKey;
// type有做id区分 所以新的组件使用需要增加新的type
const MarkConfig = ({ onChange, value, user, type = 'score', form }) => {
    const User = user.currentUser; // 登陆人信息
    const { companyId } = User;
    const { getFieldDecorator } = form;
    const columnName = type === 'score' ? '评分发起人' : '估算发起人';
    // const [nameId, setNameId] = React.useState(1);
    const [selectedRowKeys, setSelectedRowKeys] = React.useState([]);
    const dataSource = (value || []).map((item, index) => ({ key: index + 1, ...item }));
    const ref = React.useRef();
    /* -------表格行选中start---------*/
    const onSelectChange = keys => {
        setSelectedRowKeys(keys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange
    };
    /* -------表格行选中end---------*/

    /* -------表格行增减start---------*/
    const handleDelete = () => {
        const rest = value.filter(item => selectedRowKeys.indexOf(item.key) <= -1); // 过滤掉选中项的key
        const typeName = type === 'score' ? '评分' : '估算';
        if (selectedRowKeys.length > 0) {
            Modal.confirm({
                title: `确定删除选中的${typeName}规则`,
                onOk() {
                    if (onChange) {
                        onChange([...rest]);
                        setSelectedRowKeys([]);
                    }
                },
                onCancel() {}
            });
        } else {
            Modal.confirm({
                title: `请先选择要删除的${typeName}规则`
            });
        }
    };
    const handleAdd = () => {
        if (!rowKey) rowKey = dataSource.length > 0 ? Math.max(...dataSource.map(item => item.key)) : 0;

        rowKey += 1;
        onChange([...value, { key: rowKey }]);
    };
    /* -------表格行增减end---------*/

    /* -------表格单元格名称修改start---------*/

    // 更新整个组件的value
    const replaceValue = (replacement, matchIndex) => {
        const exist = value[matchIndex];
        onChange([...value.slice(0, matchIndex), { ...exist, ...replacement }, ...value.slice(matchIndex + 1)]);
    };
    const handleDemandChange = (e, key, replaceName) => {
        const Value = e;
        const matchIndex = value.findIndex(item => item.key === key);
        if (matchIndex < 0) return;
        const replacement = { [replaceName]: Value };
        replaceValue(replacement, matchIndex);
    };

    /* -------表格单元格名称修改end---------*/

    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            width: 300,
            key: 'name',
            render: (text, record) => (
                <div>
                    <Form.Item>
                        {getFieldDecorator(`${type}-${record.key}-name`, {
                            initialValue: text,
                            rules: [
                                {
                                    required: true,
                                    message: '请填写名称'
                                },
                                {
                                    max: 20,
                                    message: '限制20个字符长度'
                                },
                                {
                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                    message: '此处不能输入空格'
                                }
                            ]
                        })(
                            <Input
                                placeholder="请输入名称"
                                style={{ width: '100%' }}
                                onChange={e => handleDemandChange(e.target.value, record.key, 'name')} // 加入formgetfield获取
                            />
                        )}
                    </Form.Item>
                </div>
            )
        },
        {
            title: '执行人所属部门范围',
            dataIndex: 'departmentValue',
            key: 'departmentValue',
            width: 350,
            render: (text, record) => (
                <Form.Item>
                    {getFieldDecorator(`${type}-${record.key}-departmentValue`, {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                validator(_, values, callback) {
                                    console.log('===============================================>values', values);
                                    if (!values || (values && values.length === 0)) {
                                        callback('请选择执行人所属部门范围');
                                    }
                                    let onlyDepartment = true;
                                    const newDataSet = new Set(
                                        values && values.filter(item => typeof item !== 'string')
                                    );
                                    const restData = value && value.filter(item => item.key !== record.key);

                                    restData.forEach(item => {
                                        if (
                                            item.departmentValue &&
                                            item.departmentValue.filter(x => newDataSet.has(x)).length > 0
                                        ) {
                                            onlyDepartment = false;
                                        }
                                    });
                                    if (!onlyDepartment) {
                                        callback('执行人所属部门不可重复配置');
                                    } else {
                                        callback();
                                    }
                                }
                            }
                        ]
                    })(
                        <SelectComDepTree
                            style={{ width: '300px' }}
                            getChildByOrganizationCode={[companyId]}
                            onChange={e => {
                                handleDemandChange(e, record.key, 'departmentValue');
                                setTimeout(() => {
                                    form.validateFields();
                                }, 0); // onchange回调回调方法 会先去校验change前的value
                            }}
                            treeCheckable
                            placeholder="请选择部门"
                            getPopupContainer={dom => ref.current || dom}
                        />
                    )}
                </Form.Item>
            )
        },
        {
            title: columnName,
            key: 'employeeValue',
            dataIndex: 'employeeValue',
            width: 350,
            render: (text, record) => (
                <Form.Item>
                    {getFieldDecorator(`${type}-${record.key}-employeeValue`, {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: type === 'score' ? '请选择评分发起人' : ' 请选择估算发起人'
                            }
                        ]
                    })(
                        <SelectEmployee
                            style={{ width: '300px' }}
                            getChildByOrganizationCode={[companyId]}
                            keyType="id"
                            onChange={e => handleDemandChange(e, record.key, 'employeeValue')}
                            placeholder="请选择人员"
                            getPopupContainer={dom => ref.current || dom}
                        />
                    )}
                </Form.Item>
            )
        }
    ];
    return (
        <div style={{ marginBottom: '24px' }}>
            <span>
                （
                {type === 'score'
                    ? '配置后仅对应发起人可通过评分管理对指定部门范围内的任务发起评分'
                    : '配置后仅对应发起人可通过工作量管理对指定部门范围内的任务发起评估'}
                ）
            </span>
            <div style={{ float: 'right', marginTop: '-5px' }}>
                <a
                    onClick={() => {
                        handleDelete();
                    }}
                    style={{ marginRight: '10px' }}
                >
                    删除
                </a>
                <a
                    onClick={() => {
                        handleAdd();
                    }}
                >
                    新增
                </a>
            </div>
            <div ref={ref} style={{ maxHeight: 500, overflow: 'auto', marginTop: '10px' }}>
                <Table
                    // scroll={{ x: 'max-content' }}
                    rowClassName={() => 'add-row'}
                    rowSelection={rowSelection}
                    // components={components}
                    dataSource={dataSource}
                    pagination={false}
                    bordered
                    columns={columns}
                />
            </div>
        </div>
    );
};
export default connect(({ user }) => ({
    user
}))(MarkConfig);
